import axios from "axios";
import { getToken } from '~/utils/localStorage'
import { showMessage } from '~/utils/my-notification'
import { ADMIN_TOKEN } from '~/utils/common'
import { useRouter } from 'vue-router'
import { BASE_URL } from '~/utils/request'

const router = useRouter()

const instance = axios.create({
    baseURL: BASE_URL,
    timeout: 60000
});

// 添加请求拦截器
instance.interceptors.request.use(function (config) {
    // 从缓存中拿到token
    const token = getToken()
    if(token) {
      config.headers[ADMIN_TOKEN] = token
    }
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    // console.log('response', response)
    if(response && response.data.code === 10010) {
      showMessage(response.data.message, 'error')
      // 跳转到登录页
      return
    }
    if(response && response.data.code === 10020) {
      showMessage(response.data.message, 'error')
      return
    }
    if(response && response.data.code === 10021) {
      showMessage(response.data.message, 'error')
      // 跳转到登录页
      // router.push('/login')
      return
    }
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // console.log('error', error)
    // 对响应错误做点什么
    return Promise.reject(error);
});

export default instance;
